package ferus.tigris.lines.views;

import java.util.Random;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;

public class Sprite implements AbstractView{
	private int width;
	private int height;
	private int realWidth;
	private Point position = new Point(0, 0);

	private Bitmap sprite;

	private int spriteRowCount = 4;
	private int spriteColumnCount = 3;

	private int currentFrame = 0;
	private int currentRow = 0;
	
	private int animationDirection = 1;
	private long lastTimeAnimate = 0;
	private boolean animate = false;
	
	private long delayBetweenFrames = 100;
	private long delayAtLastFrame = 400;
	Paint paint = new Paint();

	public Sprite(Bitmap bmp, long delayBetweenFrames, int rowCount, int columnCount, int delayAtLastFrame) {
		init(bmp, delayBetweenFrames, rowCount, columnCount);
		this.delayAtLastFrame = delayAtLastFrame; 
		
	}
	
	public Sprite(Bitmap bmp, long delayBetweenFrames, int rowCount, int columnCount) {
		init(bmp, delayBetweenFrames, rowCount, columnCount);
	}

	protected void init(Bitmap bmp, long delayBetweenFrames, int rowCount,
			int columnCount) {
		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setDither(true);
		sprite = bmp;
		spriteRowCount = rowCount;
		spriteColumnCount = columnCount;
		this.delayBetweenFrames = delayBetweenFrames;
		
		width = sprite.getWidth() / spriteColumnCount;
		height = sprite.getHeight() / spriteRowCount;
	}

	private void update() {
		currentFrame = selectAnimationFrame();
		selectAnimation();
		if(currentFrame < 0) {
			resetAnimation();
		}
	}

	protected int selectAnimationFrame() {
		if(animate) {
			long time = System.currentTimeMillis();
			if(time - lastTimeAnimate > delayBetweenFrames) {
				
				currentFrame += animationDirection;
				if(currentFrame == spriteColumnCount) {
					animationDirection = -1;
					time += delayAtLastFrame;
				}

				lastTimeAnimate = time;
			}
		}
		return currentFrame;
	}

	private void resetAnimation() {
		animationDirection = 1;
		animate = false;
		currentFrame = 0;
	}

	private void selectAnimation() {
		if(!animate ) {
			Random rnd = new Random();
			if(rnd.nextInt(50) == 0) {
				animate = true;
				currentRow = rnd.nextInt(spriteRowCount);
			}
		}
	}

	private Rect spriteRect() {
		int srcX = (currentFrame % spriteColumnCount) * width;
		int srcY = currentRow * height;
		return new Rect(srcX, srcY, srcX + width, srcY + height);
	}

	private Rect animationRect() {
		int x = position.x - realWidth/2;
		int y = position.y - realWidth/2;
		return new Rect(x, y, x + realWidth, y + realWidth);
	}

	public void draw(Canvas canvas) {
		update();
		Rect src = spriteRect();
		Rect dst = animationRect();
		canvas.drawBitmap(sprite, src, dst, paint);
	}

	public void setPosition(Point position) {
		this.position.set(position.x, position.y);
	}

	public void setRealSpriteWidth(int px) {
		realWidth = px;
	}
}
